//
//  WBMainViewController.swift
//  GitWeibo
//
//  Created by 胡金东 on 2017/5/17.
//  Copyright © 2017年 胡金东. All rights reserved.
//

import UIKit
import SVProgressHUD
class WBMainViewController: UITabBarController {
    
    var timer :Timer?
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setUpChildControllers()
        setUpComposeButton()
        setUpTimer()
        
        setUpNewFeatureView()
        
        /// - 设置代理
        delegate = self
        /// - 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)

        
      }
    
            deinit{
                /// - 销毁定时器
                timer?.invalidate()
                /// - 注销通知
                NotificationCenter.default.removeObserver(self)
            }
    
    

    
    /**
     portrait  : 竖屏
     landscape : 横屏
     - 1.使用代码控制设备方向，好处，可以再需要横屏时候，单独处理
     - 2.设置支持方向之后，当前控制器及子控制器都会遵守这个方向
     - 3.如果播放视频，通常是通过 present（模型跳转） 展现的
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        return .portrait
    }
    
    func composeClick() {
        

        /// - 1.实例化视图
        let compose = WBComposeView.composeView()
        /// - 2.显示视图
        compose.show()
        
    }
    /// - 创建button
   lazy  var composeButton = UIButton(type: .custom)

    
    
}

extension WBMainViewController{

    func setUpNewFeatureView() {
        
        /// - 判断是否登录
        if !WBNetWorkSessionManager.NetWorkshared().userLogon {
            return
        }
        
        
        /// - 1.如果有新版本就显示NewFeature 否则显示Welcome
        let v = isNewVersion ? WBNewFatureView.newFature() : WBWelcomeView.welcomeView()
        
        view.addSubview(v)
        
    }
    
    /// - 定义是否有新版本
    var isNewVersion : Bool{
        
//        print("取出info.plist信息\(Bundle.main.infoDictionary)" )
        /// - 取出当前版本号
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
//        print("当前版本"+currentVersion)
        /// - 取出保存在沙盒的版本号
        let path:String = ("Version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
//          print("沙盒版本"+sandboxVersion)
        /// - 保存当前版本号
      _ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        
        return currentVersion != sandboxVersion
    }
    
}






//MARK: -  利用UITabBarControllerDelegate解决加号按钮穿帮问题，不需要再减1了

extension WBMainViewController:UITabBarControllerDelegate{
    
    @objc func userLogin (n:Notification){
        
        print("用户登录通知\(n)")
        
        var when = DispatchTime.now()
        
        
        if n.object != nil {
            
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时，需要重新登录")
            when = DispatchTime.now() + 2
        }
        
        
        DispatchQueue.main.asyncAfter(deadline: when){
            SVProgressHUD.setDefaultMaskType(.clear)
            
            let nav = UINavigationController.init(rootViewController: WBOAuthViewController())
            self.present(nav, animated: true, completion: nil)
        }
        
        
    }
   
   
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        
        /// - 1.获取控制器在数组中的索引
        let idx = (childViewControllers as NSArray).index(of: viewController)
        /// - 2.判断当前索引是首页，同时idx也是首页，重复点击首页按钮(第二次点击刷新)
        if selectedIndex == 0 && idx == selectedIndex {
            print("点击首页")
            /// - 3.让表格滚动到顶部
            /// - 获取首页控制器
            let  nav = childViewControllers[0] as! UINavigationController
            let vc = nav.childViewControllers[0] as! WBHomeViewController
            /// - 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x:0,y:-64), animated: true)
            
            
            /// - 4.tableView刷新数据(解决数据刷新bug，先滚动到顶部，在刷新)
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                
                vc.loadData()
            })
            
            /// - 5.清除 tabBarItem 的 badgeNumber
            vc.tabBarItem.badgeValue = nil
            
            UIApplication.shared.applicationIconBadgeNumber = 0
            
        }
        
        
        
        /// - 如果不是UIViewController就加载
        return !viewController.isMember(of: UIViewController.self)
    }
   
}

/// - extension 类似于 OC中的分类，在Swift中还可以用来切分代码块
/// - 可以把相近功能的函数，放在一个 extension 中
/// - 便于代码维护
/// - 和OC的分类一样，extension 中不能定义属性
extension WBMainViewController {
    
    /// - 添加定时器，刷新用户新微博条数
    func setUpTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    func updateTimer() {
        
        /// - 如果没有登录就直接返回，不用在刷新数据
        if !WBNetWorkSessionManager.NetWorkshared().userLogon {
            return;
        }
        
        WBNetWorkSessionManager.NetWorkshared().unreadCount { (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
    
    func setUpComposeButton()  {
        composeButton.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        composeButton.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted)
        
        //        composeButton.setBackgroundImage(#imageLiteral(resourceName: "new_feature_finish_button"), for: .normal)
        composeButton.setBackgroundImage(UIImage(named:"tabbar_compose"), for: .normal)
        composeButton.setBackgroundImage(UIImage(named:"tabbar_compose_highlighted"), for: .highlighted)
        
        tabBar.addSubview(composeButton)
        
        let count = CGFloat(childViewControllers.count)
        /// - 将向内缩进的宽度减少，能够让按钮的宽度变大，盖住边界，防止点出按钮盖住的控制器
//         let w = tabBar.bounds.width / count - 1
//        利用UITabBarControllerDelegate解决加号按钮穿帮问题，不需要再减1了
        let w = tabBar.bounds.width / count
        /// -  insetBy 正数向内缩进，负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        
        composeButton .addTarget(self, action: #selector(composeClick), for: .touchUpInside)
        
    }
    
  func setUpChildControllers()  {
    /// -  获取沙盒 json 路径
    let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let jsonPath = (docDir as NSString).appendingPathComponent("MainData.json")
    /// - 加载NSData
    var data = NSData(contentsOfFile: jsonPath)
    
    /// - 如果沙盒没有数据，再去访问 bundle中的数据
    if data == nil {
    /// - 从 bundle加载配置的 json数据
        let path = Bundle.main.path(forResource: "MainData.json", ofType: nil)
        data = NSData(contentsOfFile: path!)
    }
    
     /// - data这个时候一定有值
    /// - 反序列化转换成数组 防止本地bundle没有解压出数据
   guard  let array =  try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:Any]] else {
   /// - 没有数据直接返回
        return
    }
    
    
    
//    let  array = [
//            ["clsName":"WBHomeViewController", "title":"首页","imageName":"home",
//             "visitorInfo":["imageName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//            ["clsName":"WBMessageViewController", "title":"消息","imageName":"message",
//             "visitorInfo":["imageName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            /// - 创建一个空的
//            ["clsName":"UIViewController"],
//            ["clsName":"WBDiscoverViewController", "title":"发现","imageName":"discover",
//             "visitorInfo":["imageName":"visitordiscover_feed_image_smallicon","message":"登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]],
//            ["clsName":"WBPodfileViewController", "title":"我","imageName":"profile",
//             "visitorInfo":["imageName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]],
//                       ]
    
/// - 测试数据，写入到沙盒中，转换成plist文件
//    (array as NSArray).write(toFile:"/Users/hujindong/Desktop/MainData.plist", atomically: true)
    
    /// - 数组 -> json 序列化
//    let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
//    (data as NSData).write(toFile: "/Users/hujindong/Desktop/MainData.json", atomically: true)
    
    /// - 遍历数组，循环创建控制器
    var arrayM = [UIViewController]()
    for dict in array!  {
            arrayM.append(cotroller(dict: dict))
        }
        viewControllers = arrayM
        
    }
    
   
    
    private func cotroller(dict :[String : Any]) ->UIViewController{
        
        /// -1. 获取字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as?String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorInfo = dict["visitorInfo"] as?[String:String]
        
        
        else {
            return UIViewController()
            
        }
        /// - 2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.visitorInfoDict = visitorInfo;
        /// - 注意：在select状态下是不可以改变字体的大小的
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .selected)
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont .systemFont(ofSize: 14)], for: .normal)
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        let nav = WBNavigationViewController(rootViewController: vc)
        return nav
        
    }
    
}

